package com.gm.app.data;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.TypedQuery;

import com.gm.app.model.Address;
import com.gm.app.model.Place;

public class PlaceDAO extends EntityDAO {

	private static PlaceDAO dao = null;

	public static PlaceDAO get() {
		if (dao == null) {
			dao = new PlaceDAO();
		}
		return dao;
	}

	public <T extends Place> TypedQuery<T> search(String description,
			Class<T> clazz) {
		return query("select c from " + clazz.getSimpleName()
				+ " c where description like ?", clazz, description);
	}

	public static <T extends Place> T find(TypedQuery<T> q) {
		if (q != null) {
			List<T> res = q.getResultList();
			if (res != null && res.size() > 0) {
				return res.get(0);
			}
		}
		return null;
	}

	public static String format(Address addr, Boolean excludeComplement) {
		List<Object> parts = new LinkedList<Object>();
		if (addr.getStreet() != null) {
			parts.add(addr.getStreet().getDescription());
		}
		parts.add(addr.getStNumber());
		if (!excludeComplement)
			parts.add(addr.getComplement());
		List<Place> places = new LinkedList<Place>();
		places.add(addr.getDistrict());
		places.add(addr.getCity());
		places.add(addr.getState());
		places.add(addr.getCountry());
		for (Place p : places) {
			if (p != null) {
				parts.add(p.getDescription());
			}
		}
		parts.add(addr.getZip());
		StringBuilder str = new StringBuilder();
		for (Object o : parts) {
			if (o != null) {
				if (str.length() > 0)
					str.append(", ");
				str.append(String.valueOf(o));
			}
		}
		return str.toString();
	}

	public static Place get(Place p) {
		if (p != null) {
			if (p.getId() != null) {
				Place np = Place.findPlace(p.getId());
				if (np == null) {
					if (p.getDescription() != null
							&& p.getDescription().length() > 0) {
						np = Place.findPlacesByDescription(p.getDescription())
								.getSingleResult();
						if (np == null) {
							p.persist();
						}
					}
				}
			}
		}
		return p;

	}

}
